import dayjs from 'dayjs';

export function GetUnixTime() {
  // @ts-ignore
  return Date.parse(new Date()) / 1000;
}

export function GetDateValue(fields: string[]): any {
  const date = GetUnixTime();
  const obj = {};
  fields.forEach((field) => {
    obj[field] = date;
  });
  return obj;
}

export function NumberToBool(value: unknown) {
  if (value === undefined || value == '') {
    return undefined;
  }
  if (typeof value == 'boolean') {
    return value;
  }
  if (value === 1) {
    return true;
  } else if (value === 0) {
    return false;
  }
}

export function GetClientIp(req: any) {
  return (
    req.headers['x-forwarded-for'] ||
    req.ip ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress ||
    ''
  );
}

export function Ipv6ToV4(ip: string) {
  if (ip.split(',').length > 0) {
    ip = ip.split(',')[0];
  }
  ip = ip.substr(ip.lastIndexOf(':') + 1, ip.length);
  return ip;
}

export function GetUserAgent(req: any) {
  return req.headers['user-agent'];
}

export function GetLocalDate() {
  const date = new Date().valueOf();
  return new Date(date + 8 * 3600000);
}

export function GetLocalTime(
  date: string,
  format: string = 'YYYY-MM-DD HH:mm',
) {
  return dayjs(date).format(format);
}

export function encryption(message: string): string {
  const maxPreLen = 8;
  const maxPostLen = 4;
  const content = '***************';

  const messageLen = message.length;
  const preLen = Math.floor((messageLen / 5) * 2); // 40%
  const postLen = Math.floor(messageLen / 5); // 20%

  const safePreLen = preLen <= 0 ? 1 : preLen > maxPreLen ? maxPreLen : preLen;
  const safePostLen = preLen < maxPostLen ? postLen : maxPostLen;

  const preStr = message.substring(0, safePreLen);
  const endStr = message.substring(messageLen - safePostLen);

  return `${preStr}${content}${endStr}`;
}

export function getBaseUrl(url: string): string {
  try {
    const parsed = new URL(url);
    let resultUrl = `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
    // 移除末尾的斜杠
    return resultUrl.endsWith('/') ? resultUrl.slice(0, -1) : resultUrl;
  } catch (e) {
    throw new Error(`Invalid URL: ${url}`);
  }
}

export function subArray<T>(array: T[], item_num: number = 10): T[][] {
  const result: T[][] = [];

  for (let i = 0; i < array.length; i += item_num) {
    result.push(array.slice(i, i + item_num));
  }

  return result;
}
